/* 配额调整-客户间调整
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\QuotaManage\QuotaAdjust\component\CustomerForm.tsx
 * @Date: 2021-08-30 09:31:11
 * @LastEditTime: 2021-09-16 15:39:50
 */
import React, { createRef } from 'react'
import { UdForm, http, validators, IUdFormItem } from '@/lib'
import UdUploader from '@/components/UdUploader/Uploader'
import { Input, InputNumber, Radio, Select, TreeSelect, message } from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import apis from '@/apis'
import quotaApis from '@/apis/AboutQuota'
import todoApi from '@/apis/TodoList/index'
import './approve.scss'
import { TreeNodeValue } from 'antd/lib/tree-select/interface'
import moment from 'moment'
import QuotaApprove from '@/components/getQuotaApprove'
import { differenceBy } from 'lodash'
const { TextArea } = Input
const { Option } = Select
const { TreeNode } = TreeSelect
interface IProps {
  id?: number
  record: any
  handQuery?: any
  planType?: number
}
interface IState {
  record: any
  treeDataList: any
  customerList: any[]
  workFlowList: any[]
  checkPerson: any[]
  isApprove?: any
}
export default class CustomerForm extends React.Component<IProps, IState> {
  private labelCol: any = { span: 4 }
  private form: WrappedFormUtils
  private PLAN_TYPE_ENUM: any = {
    0: '计划内',
    1: '计划外',
  }
  public cRef = createRef<any>()
  state = {
    record: { modifyType: '',canResidualQuotaSum: '' },
    treeDataList: [],
    customerList: [],
    workFlowList: [],
    checkPerson: [],
    isApprove: {
      quotaAdjustReadjust: false,
    },
  }

  //调整方式change事件
  private changeModifyMode = e => {
    this.setState(preState => ({ record: { ...preState.record, modifyMode: e.target.value } }))
  }

  //调入 - 调出 客户选择事件
  private changeTransferDealer = (value?: any) => {
    const chooseTransferDealer = this.state.customerList.filter(item => item.id === value)?.[0]
    //设置 调入/调出方考核阶段剩余配额
    this.form.setFieldsValue({ transferNumber: chooseTransferDealer.residualQuota }, () => {
      this.setState(preState => ({ record: { ...preState.record, ...this.form.getFieldsValue() } }))
    })
  }

  //处理片区树数据
  private mapTree = (data: any[]) => {
    return data.map(item => {
      return (
        <TreeNode value={item.code} title={item.name} key={item.code}>
          {this.mapTree(item?.children || [])}
        </TreeNode>
      )
    })
  }

  //获取片区
  private getAreaList = (value?: any) => {
    http.get(apis.getTreeByUserRe).then(res => {
      let treeDataList = res?.data?.children || []
      this.setState({ treeDataList })
    })
  }

  componentDidMount() {
    let params = { brandCode: this.props.record['brandCode'], prodBarcode: this.props.record['prodBarcode'] }
    http.get(todoApi.getProcessKeyFlow, { params }).then(res => {
      this.setState({
        isApprove: res.data,
      })
    })
    let record = { ...this.props.record }
    let { planType, id } = this.props
    http.get(todoApi.getResidualQuotaOut, { params: { id} }).then(res => {
      this.setState(
        preState => ({
          record: {
            ...preState.record,
            canResidualQuotaSum: res.data,
          }
        })
      )
    })
    record.term = record.stageBeginTime && record.stageEndTime ? `${record.stageBeginTime}-${record.stageEndTime}` : ''
    record.modifyType = 'READJUST'
    // record.modifyMode = 'IN'
    record.planTypeText = this.PLAN_TYPE_ENUM[planType]
    this.setState({ record }, () => {
      this.getAreaList()
      this.getWorkFlow()
    })
  }

  //片区改变事件,根据片区查询客户
  private getCustomerByAreaCode = (belongAreaCode: TreeNodeValue) => {
    let {
      planType,
      record: { quotaApplyPlanId },
    } = this.props
    //选择片区后 前面所选择得客户以及考核阶段剩余配额和调整数量清空
    this.setState(
      preState => ({
        record: {
          ...preState.record,
          ...this.form.getFieldsValue(),
          quotaApplyDetailModeId: undefined,
          transferNumber: undefined,
          modifyQuota: undefined,
        },
        customerList: [],
      }),
      () => {
        http
          .get(quotaApis.quotaManagegetApplyDetailByCode, {
            params: { belongAreaCode, quotaApplyPlanId, planType },
          })
          .then(res => {
            const { data: customerList } = res
            this.setState({ customerList })
          })
      }
    )
  }

  private onOk = e => {
    this.form.validateFields((err, values) => {
      if (!err) {
        if (this.state.isApprove?.quotaAdjustReadjust && this.state.checkPerson.length === 0) {
          message.warn('请选择审批人')
          return false
        }
        e.drawerBtnLoading()
        let params = { ...this.state.record, ...values }
        params.id = this.props.id
        delete params.planTypeText
        params.stageBeginTime = moment(params.stageBeginTime).format('YYYY-MM-DD HH:mm:ss')
        params.stageEndTime = moment(params.stageEndTime).format('YYYY-MM-DD HH:mm:ss')
        if (this.state.checkPerson.length > 0) {
          params['workflowReqVos'] = {
            name: 'candidateUsers',
            userId: [this.state.checkPerson[0].id],
          }
        }
        http
          .post(quotaApis.saveOrUpdateDispatchHistory, params)
          .then(() => {
            message.success('操作成功')
            e.close()
          })
          .catch(() => {
            e.drawerBtnLoadingHide()
          })
        console.log(params)
      } else {
        console.log(err)
      }
    })
  }

  //获取审批角色
  private getWorkFlow = () => {
    http
      .get(todoApi.getAdjustNextApprove, {
        params: { brandCode: this.state.record['brandCode'], modifyType: this.state.record.modifyType || '' },
      })
      .then(res => {
        const { data } = res
        this.setState({ workFlowList: data })
      })
  }

  //选择审批人
  private handShowQuotaApprove(index) {
    this.cRef.current.handelCeck(index)
  }

  private handGetPerson(value) {
    this.setState({ checkPerson: value })
  }

  render() {
    let { record } = this.state
    let { planType } = this.props
    let transferAreaLabel = this.state.record['modifyMode'] === 'IN' ? '调出方片区' : '调入方片区'
    let transferDealerLabel = this.state.record['modifyMode'] === 'IN' ? '调出方客户' : '调入方客户'
    let formItems: IUdFormItem[] = [
      { label: '品牌公司', id: 'brandName', render: () => <Input readOnly /> },
      { label: '配额品项', id: 'prodBarname', render: () => <Input readOnly /> },
      { label: '考核年度', id: 'stageYear', render: () => <Input readOnly /> },
      { label: '考核阶段', id: 'stageName', render: () => <Input readOnly /> },
      { label: '配额有效期', id: 'term', render: () => <Input readOnly /> },
      { label: '计划类型', id: 'planTypeText', render: () => <Input readOnly /> },
      {
        label: '调整类型',
        id: 'modifyType',
        render: () => (
          <Select disabled>
            <Option value="UP">调增</Option>
            <Option value="DOWN">调减</Option>
            <Option value="ADJUST">调剂</Option>
            <Option value="READJUST">客户间调整</Option>
          </Select>
        ),
      },
      { label: '所属片区', id: 'belongAreaName', render: <Input readOnly /> },
      { label: '客户名称', id: 'dealerName', render: <Input readOnly /> },
      { label: '考核阶段剩余配额', id: 'residualQuota', render: () => <Input readOnly /> },
      { label: '考核阶段剩余配额', id: 'residualQuotaWay', render: () => <Input readOnly /> },
      { label: '可调动剩余配额', id: 'canResidualQuotaSum', render: () => <Input readOnly /> },
      {
        label: '调整方式',
        id: 'modifyMode',
        rules: [validators.required],
        render: () => {
          let numKey = planType === 1 ? 'residualQuotaWay' : 'residualQuota'
          return (
            <Radio.Group onChange={e => this.changeModifyMode(e)}>
              <Radio value="IN">调入</Radio>
              <Radio value="OUT" disabled={+record[numKey] === 0}>
                调出
              </Radio>
            </Radio.Group>
          )
        },
      },
      {
        label: transferAreaLabel,
        id: 'transferArea',
        rules: [validators.required],
        render: () => (
          <TreeSelect
            showSearch
            treeNodeFilterProp="title"
            onChange={(value, label, extra) => {
              this.getCustomerByAreaCode(value)
            }}
          >
            {this.mapTree(this.state.treeDataList)}
          </TreeSelect>
        ),
      },
      {
        label: transferDealerLabel,
        id: 'quotaApplyDetailModeId',
        rules: [validators.required],
        render: () => (
          <Select onChange={value => this.changeTransferDealer(value)} showSearch optionFilterProp="children">
            {this.state.customerList.map(item => (
              <Option key={item.id} value={item.id}>
                {item.dealerName}
              </Option>
            ))}
          </Select>
        ),
      },
      {
        label: '考核阶段剩余配额',
        id: 'transferNumber',
        render: () => <Input readOnly />,
      },
      {
        label: '调整数量',
        id: 'modifyQuota',
        rules: [validators.numberPlus, validators.required],
        render: (
          <InputNumber
            min={1}
            max={
              this.state.record['modifyMode'] === 'IN'
                ? this.state.record['transferNumber']
                : planType === 0
                ? this.state.record['residualQuota']
                : this.state.record['residualQuotaWay']
            }
            precision={0}
            style={{ width: '100%' }}
            readOnly={ !((this.state.record['modifyMode'] == 'IN' && (Number(this.state.record['transferNumber']) > 0)) || (this.state.record['modifyMode'] == 'OUT' && (Number(this.state.record['canResidualQuotaSum']) > 0)))}
          />
        ),
      },
      { label: '备注信息', id: 'remark', rules: [validators.required], render: <TextArea rows={3} maxLength={200} /> },
      {
        label: '凭证附件',
        id: 'quotaApplyDetailFileRespVoList',
        render: <UdUploader form={this.form} extra="支持扩展名：.jpg .png .xls .doc" />,
      },
    ]
    const filterFiles: object = {
      1: [{ id: 'residualQuota' }],
      0: [{ id: 'residualQuotaWay' }],
    }
    formItems = differenceBy(formItems, filterFiles[planType], 'id') as IUdFormItem[]
    return (
      <>
        <UdForm
          getForm={form => (this.form = form)}
          labelCol={this.labelCol}
          items={formItems}
          values={this.state.record}
        />
        {this.state.isApprove?.quotaAdjustReadjust && <h4>审批流程</h4>}
        {this.state.isApprove?.quotaAdjustReadjust && (
          <div className="approve-wrap">
            <div className="node-name-wrap">
              <div className="approve-title">节点名称：</div>
              <span className="circle-point"></span>
              <div>{this.state.workFlowList[0]?.nodeName || '暂无'}</div>
            </div>
            <div className="person-name-wrap">
              <div className="approve-title">审批人:</div>
              <div
                className={this.state.checkPerson[0]?.realName ? 'add-plus-name' : 'add-plus'}
                onClick={() => {
                  this.handShowQuotaApprove(0)
                }}
              >
                {this.state.checkPerson[0]?.realName || '+'}
              </div>
            </div>
          </div>
        )}
        <QuotaApprove
          handCilck={this.handGetPerson.bind(this)}
          cRef={this.cRef}
          ids={this.state.workFlowList[0]?.roleIds}
        />
      </>
    )
  }
}
